#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""followup_api.py
最小随访记录 API（小程序 stub）。
若后续有正式随访业务模型，可替换为真实实现：
 - 表结构: followup_records (id, user_id, student_id, title, content, status, priority, created_at, updated_at)
 - 状态：pending/completed/overdue
本实现只满足：列表、分页、状态更新。
"""
from flask import request, jsonify
from flask_jwt_extended import jwt_required, get_jwt_identity
from datetime import datetime
from backend.api.miniprogram import miniprogram_bp
from backend.infrastructure.database import db
from backend.models.followup import FollowupRecord

@miniprogram_bp.route('/followup_records/list', methods=['GET'])
@jwt_required()
def followup_list():
    page = request.args.get('page', 1, type=int)
    limit = request.args.get('limit', 20, type=int)
    student_id = request.args.get('student_id', type=int)
    q = FollowupRecord.query
    if student_id:
        q = q.filter(FollowupRecord.student_id == student_id)
    total = q.count()
    items = q.order_by(FollowupRecord.followup_date.desc(), FollowupRecord.created_at.desc()).offset((page-1)*limit).limit(limit).all()
    return jsonify({'success': True, 'data': {'records': [i.to_dict() for i in items], 'pagination': {'page': page, 'per_page': limit, 'total': total}}})

@miniprogram_bp.route('/followup_records/<int:record_id>', methods=['GET'])
@jwt_required()
def followup_detail(record_id):
    """获取随访记录详情"""
    rec = FollowupRecord.query.get(record_id)
    if not rec:
        return jsonify({'success': False, 'message': '记录不存在'}), 404
    return jsonify({'success': True, 'data': rec.to_dict()})

@miniprogram_bp.route('/followup_records/<int:record_id>', methods=['PUT'])
@jwt_required()
def followup_update(record_id):
    rec = FollowupRecord.query.get(record_id)
    if not rec:
        return jsonify({'success': False, 'message': '记录不存在'}), 404
    data = request.get_json() or {}
    # 允许更新的核心字段示例
    mutable_fields = [
        'intervention_satisfaction','intervention_effect_evaluation','intervention_compliance',
        'side_effects','vision_change_perception','vision_improvement_details','vision_concern_areas',
        'daily_eye_use_time','content','feedback'
    ]
    for f in mutable_fields:
        if f in data:
            setattr(rec, f, data[f])
    rec.updated_at = datetime.utcnow()
    db.session.commit()
    return jsonify({'success': True, 'data': rec.to_dict(), 'message': '更新成功'})
